<template>
  <div class="info-dialog">
    <el-dialog
      :visible.sync="visible"
      :title="title"
      :modal-append-to-body="true"
      :append-to-body="true"
      :destroy-on-close="false"
      :modal="true"
      :close-on-click-modal="false"
      top="10vh"
      width="550px"
      @closed="closed"
    >
      <el-form ref="formData" :model="formData" :rules="rules">
        <el-form-item label-width="100px" label="账号" prop="username">
          <el-input v-model="formData.username" placeholder="请输入账号" autocomplete="off" />
        </el-form-item>
        <el-form-item label-width="100px" label="姓名" prop="name">
          <el-input v-model="formData.name" placeholder="请输入姓名" autocomplete="off" />
        </el-form-item>
        <el-form-item label-width="100px" label="联系电话" prop="phone">
          <el-input v-model="formData.phone" placeholder="请输入电话" autocomplete="off" />
        </el-form-item>

        <el-form-item label-width="100px" label="所属部门" prop="userDepts">
          <treeselect v-model="userDepts"
          :multiple="true"
          :flat="true"
          noOptionsText="无数据."
          noResultsText="无数据."
          noChildrenText="无数据."
          :normalizer="normalizer"
          placeholder="请选择..."
          :options="deptOptions" />
        </el-form-item>

        <el-form-item label-width="100px" label="所属角色" prop="userRoles">
          <el-select v-model="userRoles" multiple placeholder="请选择" style="width: 100%;">
            <el-option
              v-for="item in roleOptions"
              no-data-text="无数据."
              no-match-text="无匹配数据."
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>

      </el-form>

      <div style="text-align: right;">
        <el-button @click="closed" :loading="loading">取 消</el-button>
        <el-button type="primary" :loading="loading" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>

  // import the component
  import Treeselect from '@riophae/vue-treeselect'
  // import the styles
  import '@riophae/vue-treeselect/dist/vue-treeselect.css'

  import {
    saveUser,
    getUserDeptIdsById,
    getUserRoleIdsById
  } from '@/api/system/user'

  import {
    getDeptOptionsTree
  } from '@/api/system/dept'

  import {
    getRoleOptions
  } from '@/api/system/role'

  export default {
    name: 'InfoDialog',
    components: {
      Treeselect
    },
    props: {
      properties: {
        type: Object,
        default: () => ({})
      }
    },
    computed:{

    },
    watch:{
      properties: {
        handler: function(value) {
          this.visible = value.visible
          if (value.data) {
            this.formData.id = value.data.id || ''
            this.formData.username = value.data.username || ''
            this.formData.name = value.data.name || ''
            this.formData.phone = value.data.phone || ''
          } else {
            this.formData.id = ''
            this.formData.username = ''
            this.formData.name = ''
            this.formData.phone = ''
          }
          if (value.type) {
            this.type = value.type
            if (value.type === '0') {
              this.title = '新增'
            }
            if (value.type === '1') {
              this.title = '编辑'
            }
          }
        },
        immediate: true,
        deep: false
      }
    },
    data(){
      return {
        visible:false,
        title:'',
        loading:false,
        formData: {
          id: '',
          username: '',
          name: '',
          phone: '',
        },
        userDepts: null,
        deptOptions: [],
        userRoles:null,
        roleOptions:[],
        rules: {
          name: [{
            required: true,
            message: '请输入姓名或昵称',
            trigger: 'blur'
          },
          {
            min: 1,
            max: 50,
            message: '长度在 1 到 50 个字符',
            trigger: 'blur'
          }
          ],
          username: [{
            required: true,
            message: '请输入用户名',
            trigger: 'blur'
          },
          {
            min: 2,
            max: 50,
            message: '长度在 2 到 50 个字符',
            trigger: 'blur'
          }
          ],
          phone: [{
              required: true,
              message: '请输入手机号码（多个号码请用‘,’分割）',
              trigger: 'blur'
            },
            {
              min: 11,
              max: 50,
              message: '长度在 11 到 50 个字符',
              trigger: 'blur'
            }
          ]
        }
      }
    },
    created() {
      this.getDeptOptionsTree();
      this.getRoleOptions();
    },
    methods:{
      normalizer(node){
          //去掉children=[]的children属性
          if(node.children && !node.children.length){
              delete node.children;
          }
          return {
              id: node.id,
              label:node.name,
              children:node.children
          }
      },
      getDeptOptionsTree(){
        getDeptOptionsTree().then(response => {
          if(200==response.code){
            this.deptOptions=response.data;
            this.getUserDeptIdsById();
          }
        }).catch(err => {
          console.log(err);
        })
        .finally(() => {
        })
      },
      getUserDeptIdsById(){
        getUserDeptIdsById({
          userId:this.formData.id
        }).then(response => {
          if(200==response.code){
            this.userDepts=response.data;
          }
        }).catch(err => {
          console.log(err);
        })
        .finally(() => {
        })
      },
      getRoleOptions(){
        getRoleOptions().then(response => {
          if(200==response.code){
            this.roleOptions=response.data;
            this.getUserRoleIdsById();
          }
        }).catch(err => {
          console.log(err);
        })
        .finally(() => {
        })
      },
      getUserRoleIdsById(){
        getUserRoleIdsById({
          userId:this.formData.id
        }).then(response => {
          if(200==response.code){
            this.userRoles=response.data;
          }
        }).catch(err => {
          console.log(err);
        })
        .finally(() => {
        })
      },
      submitForm: function() {
        this.$refs.formData.validate((valid) => {
          if (valid) {
            this.loading = true
            saveUser({
              user:this.formData,
              deptIds:this.userDepts!=null && this.userDepts!='' && this.userDepts!=undefined ?  this.userDepts.join():'',
              roleIds:this.userRoles!=null && this.userRoles!='' && this.userRoles!=undefined ?  this.userRoles.join():''
            }).then(rsp => {
              this.$message({
                type: 'success',
                message: this.type === '1' ? '修改成功!' : '添加成功!'
              })
              this.closed()
            }).catch(err => {
              console.log(err);
            })
            .finally(() => {
              this.loading = false
            })
          }
        })
      },
      closed: function() {
        this.$emit('closed', false)
      },
    }
  }

</script>

<style>
</style>
